<?php

namespace app\admin\service;

use app\admin\model\admin\Admin;
use app\admin\model\admin\AdminLog;
use support\Response;

class LoginService extends BaseService
{
    public function __construct(Admin $model)
    {
        $this->model = $model;
    }

    public function loginCheck($request, $where): Response
    {
        $input = $request->post();

        $data = $this->model->where($where)->find();
        if (empty($data)) {
            return json(['code' => -1, 'msg' => '登录用户不存在']);
        }
        if ($data['status'] != 1) {
            return json(['code' => -1, 'msg' => '该用户已被禁止登录']);
        }
        if ($data['password'] <> md5($input['password'] . $data['salt'])) {
            return json(['code' => -1, 'msg' => '您输入的密码不正确']);
        }

        $logModel = new AdminLog;
        $logModel->admin_id = $data['id'];
        $logModel->ip = $request->getRealIp($safe_mode=true);
        $logModel->act = 'login';
        $logModel->note = '登录';
        $logModel->save();

        $request->session()->set('username', $data['username']);

        $data = [
            'url' => '/admin'
        ];
        return json(['code' => 1, 'msg' => 'ok', 'data' => $data]);
    }

    public function loginOut($request): Response
    {
        $session = $request->session();
        $session->forget('username');

//        $data = [
//            'url' => '/admin/login/index'
//        ];
//        return json(['code' => 1, 'msg' => 'ok', 'data' => $data]);

        return redirect('/admin/login/index');
    }

}